
//
// 121213 - AH - Created.
// 121227 - AH - Writes XML about how logs: which classes, methods and if 
//               logging is turned on. 
//               

package org.japril.jutil.logging;

import java.io.PrintStream;
import java.io.PrintWriter;

/**
 * <p>
 *   {@link LogSink} that logs to 
 *   {@link System#out standard out} or a given 
 *   {@link PrintWriter} and have means to turn of logging.
 * </p>
 * @author Arne Halvorsen (AH)
 */
public class PrintLogSink implements LogSink 
{
  private PrintStream m_ps=null;
  
  private PrintWriter m_pw=null;
  
  private LogFormater m_lf=new DefaultLogFormater();
  
  /**
   * <p>
   *   Constructor.
   * </p>
   */
  public PrintLogSink(){ m_ps=System.out; }
  
  /**
   * <p>
   *   Constructor.
   * </p>
   * @param pw {@link PrintWriter} to log to.
   */
  public PrintLogSink(PrintWriter pw){ setWriter(pw); }
  
  /**
   * <p>
   *   Sets
   *   {@link PrintWriter} to log to. 
   * </p>
   * @param pw Writer, if {@code null} logs to
   *           {@link System#out standard out}.
   */
  public final void setWriter(PrintWriter pw)
  {
    if (pw==null)
    {
      m_ps=System.out;
      m_pw=null;
    }
    else
    {
      m_pw=pw;
      m_ps=null;
    }
  }
  
  /**
   * <p>
   *   Sets 
   *   {@link LogFormater} to use.
   * </p>
   * @param lf {@link LogFormater} to set, if {@code null} logs unformatted.
   */
  public void setLogFormater(LogFormater lf){ m_lf=lf; }
  
  // Specified in LogSink.
  public final void log(Class<?> clazz, String method, String msg)
  {
    msg=(m_lf==null) ? msg : m_lf.format(clazz, method, msg);
    rlog(clazz, method, msg); // well now it is not raw anymore.
  }
  
  // Specified in LogSink.
  public final void rlog(Class<?> clazz, String method, String msg)
  { 
    msg=(msg==null) ? "" : msg.trim();
    if (msg.length()==0) return;
    if (m_ps!=null){ m_ps.println(msg); m_ps.flush(); return; }
    if (m_pw!=null){ m_pw.println(msg); m_pw.flush(); return; }
  }

}
